<template>
  <div id="app">
    <form action="">
      姓名：<input type="text" v-model="stu.uname" /><br />
      年龄：<input type="text" v-model.number="stu.age" /><br />
      性别：<input type="radio" name="sex" value="男" v-model="stu.sex" />男
      <input type="radio" name="sex" value="女" v-model="stu.sex" />女
      <br />
      <button @click.prevent="add">添加/修改</button>
    </form>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { id: 1, uname: "张三", age: 20, sex: "男" },
        { id: 2, uname: "李四", age: 30, sex: "女" },
      ],
      stu: {
        uname: "",
        age: "",
        sex: "男",
      },
      id: null,
    };
  },
  methods: {
    del(id) {
      return (this.list = this.list.filter((item) => item.id !== id));
    },
    edit(id) {
      let row = this.list.find((item) => item.id === id);
      // console.log(row);
      this.stu = { ...row };
      this.id = row.id;
    },
    add(){
      if(this.id === null){
         this.stu.id = +new Date();
        this.list.push({ ...this.stu });
      }else{
        let index = this.list.findIndex((item) => item.id === this.id);
        this.list.splice(index, 1, { ...this.stu });
        this.id = null;
      }
       this.stu = {
        uname: "",
        age: "",
        sex: "男",
      };
    }
  },
};
</script>

<style>
</style>